package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@Validated
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    //用户住册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {

        //查询用户
        User user = userService.findByName(username);

        //判断是否存在该用户
        if (user == null) {
            //没被占用注册
            userService.register(username, password);
            return Result.success();
        }
        else {
            return Result.error("用户已存在");
        }

    }

    //用户登录
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password)
    {
        //查询用户
        User user=userService.findByName(username);

        //判断用户是否存在
        if(user==null)
        {
            return Result.error("用户名错误");
        }

        //校验用户密码
        if(Md5Util.getMD5String(password).equals(user.getPassword()))
        {
            Map<String,Object> claim=new HashMap<>();

            claim.put("id",user.getId());
            claim.put("username",user.getUsername());
            //获取令牌token
            String token= JwtUtil.genToken(claim);

            //把token存取到redis中
           ValueOperations<String,String> operations =stringRedisTemplate.opsForValue();

           operations.set(token,token,1, TimeUnit.HOURS);

            return Result.success(token);
        }

        return Result.error("密码错误");


    }



    //获取用户详细信息
    @GetMapping("/userInfo")
    public Result getUserInfo()
    {
//        //通过令牌获取请求头获取用户信息
//        Map<String, Object> map = JwtUtil.parseToken(token);
//@RequestHeader("Authorization")String token
//        String username= (String) map.get("username");

        //通过ThreadLocal获取用户数据
        Map<String,Object> map = ThreadLocalUtil.get();

        String username=(String) map.get("username");


        User user=userService.findByName(username);

        return Result.success(user);
    }


    //更新用户基本信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user)
    {

        userService.update(user);

        return Result.success();

    }


    // 更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl)
    {
        //获取用户id
       Map<String,Object> map=ThreadLocalUtil.get();

      Integer id =(Integer) map.get("id");

        userService. updateAvatar(avatarUrl,id);

        return Result.success();

    }


    // 更新用户密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token)
    {
        //获取前端返回的数据
        String olderPwd=params.get("old_pwd");
        String newPwd=params.get("new_pwd");
        String rePwd=params.get("re_pwd");

        //校验输入的密码是否为空
        if(!StringUtils.hasLength(olderPwd)||!StringUtils.hasLength(newPwd)||!StringUtils.hasLength(rePwd))
        {
            return Result.error("缺少必要的参数");
        }

        //校验oldPwd和数据库中的密码是否一致
        Map<String,Object> map=ThreadLocalUtil.get();
        String username=(String) map.get("username");
        User loginUser=userService.findByName(username);

        if(!loginUser.getPassword().equals(Md5Util.getMD5String(olderPwd)))
        {
            return Result.error("原密码填写不正确");
        }

        //校验新密码再次输入的正确性
        if(!rePwd.equals(newPwd))
        {
            return Result.error("两次输入的新密码不一致");
        }


        userService.updatePwd(newPwd);

        //删除Redis中的对应的Token

        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

        operations.getOperations().delete(token);

        return Result.success();




    }







}
